import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AppService } from './app.service';
import { AppConfigValidationSchema } from './config/app.env.schema';
import { MinioConfigValidationSchema } from './config/minio.env.schema';
import { PgConfigValidationSchema } from './config/pg.env.schema';
import { CurrentUser } from './modules/auth/decorators/current-user.decorator';
import { AuthService } from './modules/auth/auth.service';
import { JwtStrategyGuard } from './modules/auth/guards/jwt.strategy.guard';
import { LocalStrategyGuard } from './modules/auth/guards/local.strategy.guard';
import { CreateUserDto } from './modules/user/dto/create-user.dto';
import { UserService } from './modules/user/user.service';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly authService: AuthService,
    private readonly userService: UserService,
    private readonly configService: ConfigService,
  ) {}

  @UseGuards(LocalStrategyGuard)
  @Get()
  getHello(): string {
    console.log(this.configService.get('MINIO_ACCESS_KEY'));
    return this.appService.getHello();
  }

  @UseGuards(JwtStrategyGuard)
  @Get('/config')
  getConfig(@CurrentUser() user: any, @CurrentUser('id') userId: any) {
    const formatObj = (obj) => {
      return Object.keys(obj).reduce(
        (t, v) => ({
          ...t,
          [v]: this.configService.get(v),
        }),
        {},
      );
    };
    return {
      user,
      userId,
      appConfig: formatObj(AppConfigValidationSchema),
      pgConfig: formatObj(PgConfigValidationSchema),
      minioConfig: formatObj(MinioConfigValidationSchema),
    };
  }

  @Post('/login/local')
  async loginLocal(
    @Body('email') email: string,
    @Body('password') password: string,
  ) {
    return this.authService.validateUser(email, password);
  }

  @Post('/register')
  async register(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  @Post('/login/jwt')
  async login(@Body('id') id: string) {
    return this.authService.jwtSign(id);
  }
}
